Page({
  data: {
    weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    timeSlots: [
      { id: 1, time: '08:00-09:40', name: '第1节' },
      { id: 2, time: '10:00-11:40', name: '第2节' },
      { id: 3, time: '14:00-15:40', name: '第3节' },
      { id: 4, time: '16:00-17:40', name: '第4节' },
      { id: 5, time: '19:00-20:40', name: '第5节' },
      { id: 6, time: '20:40-22:15', name: '第6节' }
    ],
    schedule: {}, // 课表数据 {day_slot: {courseName, teacher, location, courseId, colorClass}}
    showAddCourseModal: false,
    editingCourse: null,
    showManageModal: false,
    
    // 课程颜色主题数组
    courseColors: [
      'course-color-1', 'course-color-2', 'course-color-3', 'course-color-4',
      'course-color-5', 'course-color-6', 'course-color-7', 'course-color-8',
      'course-color-9', 'course-color-10', 'course-color-11', 'course-color-12'
    ],
    usedColors: {}, // 记录已使用的颜色 {courseName: colorClass}
    
    // 周数选择器数据
    weekNumbers: [],
    
    // 添加课程表单数据
    courseForm: {
      courseName: '',
      teacher: '',
      location: '',
      selectedDay: '',
      selectedSlot: '',
      weekStart: 1,
      weekEnd: 20
    },
    
    currentWeek: 1, // 当前显示的周数
    totalWeeks: 25, // 总周数
    filteredSchedule: {}, // 根据当前周过滤后的课表
  },

  onLoad: function() {
    this.setCurrentWeek();
    this.initWeekNumbers();
    this.loadSchedule();
  },

  // 临时方法：为现有课程添加颜色
  addColorsToExistingCourses: function() {
    const schedule = this.data.schedule;
    const updatedSchedule = {};
    
    // 兼容微信小程序的遍历方式
    for (let key in schedule) {
      if (schedule.hasOwnProperty(key)) {
        const course = schedule[key];
        if (course && course.courseName && !course.colorClass) {
          const colorClass = this.assignColorToCourse(course.courseName);
          // 兼容微信小程序的对象展开
          updatedSchedule[key] = Object.assign({}, course, { colorClass: colorClass });
        
        } else {
          updatedSchedule[key] = course;
        }
      }
    }
    
    this.setData({ schedule: updatedSchedule }, () => {
      this.filterScheduleByWeek();
    });
  },
  
  // 初始化周数数据
  initWeekNumbers: function() {
    const weekNumbers = [];
    for (let i = 1; i <= 25; i++) {
      weekNumbers.push(`第${i}周`);
    }
    this.setData({ weekNumbers });
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.loadSchedule();
  },

  // 导航返回
  navigateBack: function() {
    wx.navigateBack({
      delta: 1,
      fail: function() {
        // 如果返回失败（没有上一页），则跳转到首页
        wx.switchTab({
          url: '/pages/index/index',
        });
      }
    });
  },

  // 设置当前周信息（学期周数）
  setCurrentWeek: function() {
    // 这里可以根据学期开始时间计算当前是第几周
    // 暂时设置为第1周，后续可以优化
    this.setData({
      currentWeek: 1
    });
  },

  // 显示管理弹窗
  showManageModal: function() {
    this.setData({
      showManageModal: true
    });
  },

  // 隐藏管理弹窗
  hideManageModal: function() {
    this.setData({
      showManageModal: false
    });
  },

  // 管理操作
  onManageAction: function(e) {
    const action = e.currentTarget.dataset.action;
    
    switch(action) {
      case 'clear':
        this.clearSchedule();
        break;
      default:
        break;
    }
    
    this.hideManageModal();
  },

  // 上一周
  prevWeek: function() {
    if (this.data.currentWeek > 1) {
      this.setData({
        currentWeek: this.data.currentWeek - 1
      }, () => {
        this.filterScheduleByWeek();
      });
    }
  },

  // 下一周
  nextWeek: function() {
    if (this.data.currentWeek < this.data.totalWeeks) {
      this.setData({
        currentWeek: this.data.currentWeek + 1
      }, () => {
        this.filterScheduleByWeek();
      });
    }
  },

  // 清空课表
  clearSchedule: function() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有课程吗？此操作不可恢复！',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          // 调用API清空课表
          this.clearScheduleFromServer();
        }
      }
    });
  },

  // 从服务器清空课表
  clearScheduleFromServer: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '清空中...'
    });

    const { getApiUrl } = require('../../config/config.js');

    wx.request({
      url: getApiUrl('/api/course-schedule/clear'),
      method: 'DELETE',
      data: {
        userId: userInfo.id
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data && res.data.code === 200) {
          // 清空成功，刷新课表
          this.refreshSchedule();
          wx.showToast({
            title: '课表已清空',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data?.msg || '清空失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 加载课表数据
  loadSchedule: function() {
    // 直接从服务器加载最新数据
    this.loadScheduleFromServer();
  },
  
  // 从服务器加载课表数据
  loadScheduleFromServer: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.id) {
      this.setData({ schedule: {}, filteredSchedule: {} });
      return;
    }
    
    wx.showLoading({
      title: '加载课表中...'
    });
    
    const { getApiUrl } = require('../../config/config.js');
    const apiUrl = getApiUrl('/api/course-schedule/list');
    const requestData = {
      userId: userInfo.id,
      _t: Date.now() // 添加时间戳避免缓存
    };
    const token = wx.getStorageSync('token');
    
    
    wx.request({
      url: apiUrl,
      method: 'GET',
      data: requestData,
      header: {
        'content-type': 'application/json',
        'token': token
      },
      success: (res) => {
        wx.hideLoading();
        
        
        if (res.data && res.data.code === 200 && res.data.data) {
          
          // 转换服务器数据格式为本地格式
          const schedule = this.convertServerDataToLocal(res.data.data);
        
          
          // 直接设置从服务器获取的数据
          this.setData({ schedule }, () => {
            // 为现有课程添加颜色
            this.addColorsToExistingCourses();
          });
        } else {
          // 没有数据或请求失败，显示空课表
          this.setData({ schedule: {}, filteredSchedule: {} });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        
        
        // 网络错误，显示空课表
        this.setData({ schedule: {}, filteredSchedule: {} });
        
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },
  
  // 转换服务器数据格式
  convertServerDataToLocal: function(serverData) {
    const localSchedule = {};
    
    
    
    if (Array.isArray(serverData)) {
      serverData.forEach((course, index) => {
   
        
        // 解析 classTime 来确定 day 和 slot
        const { day, slot } = this.parseClassTime(course.classTime);
        
        if (day !== null && slot !== null) {
          const courseKey = `${day}_${slot}`;
          const colorClass = this.assignColorToCourse(course.courseName);
            
          localSchedule[courseKey] = {
            courseName: course.courseName,
            teacher: course.teacherName,
            location: course.classroom,
            courseId: course.id,
            weekStart: course.weekStart || 1,
            weekEnd: course.weekEnd || 20,
            colorClass: colorClass
          };
        } else {
        
        }
      });
    } else {
      
    }
    
   
    return localSchedule;
  },
  
  // 解析课程时间字符串
  parseClassTime: function(classTime) {
    
    const dayMap = {
      '周一': 0, '周二': 1, '周三': 2, '周四': 3, '周五': 4, '周六': 5, '周日': 6,
      'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6
    };
    
    // 时间段映射 - 根据时间段确定节次
    const timeSlotMap = {
      '08:00-09:40': 1,
      '10:00-11:40': 2,
      '14:00-15:40': 3,
      '16:00-17:40': 4,
      '19:00-20:40': 5,
      '20:40-22:15': 6
    };
    
    // 默认返回值
    let day = null, slot = null;
    
    if (typeof classTime === 'string') {
      // 首先尝试匹配英文格式 "Monday:08:00-09:40"
      const englishMatch = classTime.match(/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday):(.+)$/);
      
      if (englishMatch) {
        const dayName = englishMatch[1];
        const timeRange = englishMatch[2];
        
        day = dayMap[dayName];
        slot = timeSlotMap[timeRange];
        
      } else {
        // 如果英文格式匹配失败，尝试中文格式 "周一第1节"
        const chineseMatch = classTime.match(/(周[一二三四五六日]).*?第?(\d+)节?/);
        
        if (chineseMatch) {
          day = dayMap[chineseMatch[1]] || null;
          slot = parseInt(chineseMatch[2]) || null;
        } else {
        }
      }
    } else {
    }
    
    return { day, slot };
  },


  // 过滤当前周的课表
  filterScheduleByWeek: function() {
    const currentWeek = this.data.currentWeek;
    const schedule = this.data.schedule;
    const filteredSchedule = {};

    

    // 兼容微信小程序的遍历方式
    for (let key in schedule) {
      if (schedule.hasOwnProperty(key)) {
        const course = schedule[key];
        const weekStart = course.weekStart || 1;
        const weekEnd = course.weekEnd || 20;
        
        // 只有当前周在课程的周数范围内才添加到过滤后的课表
        if (currentWeek >= weekStart && currentWeek <= weekEnd) {
          filteredSchedule[key] = course;
         
        }
      }
    }


    this.setData({ filteredSchedule });
  },

  // 更新课表后刷新显示
  refreshSchedule: function() {
    this.loadScheduleFromServer();
  },

  // 显示添加课程弹窗
  showAddCourseModal: function(e) {
    const dataset = e.currentTarget.dataset;
    const day = dataset.day !== undefined ? dataset.day : 0;
    const slot = dataset.slot !== undefined ? dataset.slot : 1;
    
    // 检查是否已有课程
    const courseKey = `${day}_${slot}`;
    const existingCourse = this.data.schedule[courseKey];
    
    if (existingCourse) {
      // 编辑现有课程
      this.setData({
        showAddCourseModal: true,
        editingCourse: courseKey,
        courseForm: {
          courseName: existingCourse.courseName,
          teacher: existingCourse.teacher,
          location: existingCourse.location,
          selectedDay: day,
          selectedSlot: slot,
          weekStart: existingCourse.weekStart || 1,
          weekEnd: existingCourse.weekEnd || 20
        }
      });
    } else {
      // 添加新课程
      this.setData({
        showAddCourseModal: true,
        editingCourse: null,
        courseForm: {
          courseName: '',
          teacher: '',
          location: '',
          selectedDay: day,
          selectedSlot: slot,
          weekStart: 1,
          weekEnd: 20
        }
      });
    }
  },

  // 隐藏添加课程弹窗
  hideAddCourseModal: function() {
    this.setData({
      showAddCourseModal: false,
      editingCourse: null,
      courseForm: {
        courseName: '',
        teacher: '',
        location: '',
        selectedDay: '',
        selectedSlot: '',
        weekStart: 1,
        weekEnd: 20
      }
    });
  },

  // 阻止弹窗关闭（用于阻止事件冒泡）
  preventModalClose: function() {
    // 空函数，用于阻止事件冒泡到 modal-overlay
  },

  // 处理表单输入
  handleFormInput: function(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [`courseForm.${field}`]: value
    });
  },
  
  // 开始周数选择
  onWeekStartChange: function(e) {
    const weekStart = parseInt(e.detail.value) + 1;
    let { weekEnd } = this.data.courseForm;
    
    // 确保结束周数不小于开始周数
    if (weekEnd < weekStart) {
      weekEnd = weekStart;
    }
    
    this.setData({
      'courseForm.weekStart': weekStart,
      'courseForm.weekEnd': weekEnd
    });
  },
  
  // 结束周数选择
  onWeekEndChange: function(e) {
    const weekEnd = parseInt(e.detail.value) + 1;
    let { weekStart } = this.data.courseForm;
    
    // 确保开始周数不大于结束周数
    if (weekStart > weekEnd) {
      weekStart = weekEnd;
    }
    
    this.setData({
      'courseForm.weekStart': weekStart,
      'courseForm.weekEnd': weekEnd
    });
  },

  // 保存课程
  saveCourse: function() { 
    const { courseName, teacher, location, selectedDay, selectedSlot, weekStart, weekEnd } = this.data.courseForm;
    
    if (!courseName.trim()) {
      wx.showToast({
        title: '请输入课程名称',
        icon: 'none'
      });
      return;
    }
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: this.data.editingCourse ? '修改中...' : '添加中...'
    });
    
    // 准备API请求数据
    const courseData = {
      userId: userInfo.id,
      courseName: courseName.trim(),
      teacherName: teacher.trim(),
      credit: 2, // 默认学分
      courseType: 1, // 默认必修课
      courseDescription: '',
      examType: 0, // 默认考试
      classroom: location.trim(),
      classTime: this.getClassTimeString(selectedDay, selectedSlot),
      weekStart: weekStart,
      weekEnd: weekEnd
    };
    
    // 如果是编辑模式，添加课程ID
    if (this.data.editingCourse) {
      const existingCourse = this.data.schedule[this.data.editingCourse];
      if (existingCourse && existingCourse.courseId) {
        courseData.id = existingCourse.courseId;
      }
    }
    
    const { getApiUrl } = require('../../config/config.js');
    
    // 根据是否是编辑模式选择不同的API端点和HTTP方法
    const apiEndpoint = this.data.editingCourse ? '/api/course-schedule/edit' : '/api/course-schedule/create';
    const httpMethod = this.data.editingCourse ? 'PUT' : 'POST';
    
    wx.request({
      url: getApiUrl(apiEndpoint),
      method: httpMethod,
      data: courseData,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data && res.data.code === 200) {
          // API调用成功，重新加载课表数据
          this.hideAddCourseModal();
          this.refreshSchedule();
          
          // 清理未使用的颜色记录
          this.cleanupUnusedColors();
          
          wx.showToast({
            title: this.data.editingCourse ? '修改成功' : '添加成功',
            icon: 'success'
          });
          wx.vibrateShort();
        } else {
          // API调用失败
          wx.showToast({
            title: res.data?.msg || '保存失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        
        // 网络错误
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
      }
    });
  },
  
  
  // 生成课程时间字符串
  getClassTimeString: function(dayIndex, slotId) {
    const weekDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    const timeSlot = this.data.timeSlots.find(slot => slot.id == slotId);
    
    if (timeSlot) {
      return `${weekDays[dayIndex]}:${timeSlot.time}`;
    }
    return '';
  },

  // 删除课程
  deleteCourse: function() {
    if (!this.data.editingCourse) return;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这门课程吗？',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          this.deleteCourseFromServer();
        }
      }
    });
  },

  // 从服务器删除课程
  deleteCourseFromServer: function() {
    const existingCourse = this.data.schedule[this.data.editingCourse];
    if (!existingCourse || !existingCourse.courseId) {
      wx.showToast({
        title: '课程信息不完整',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '删除中...'
    });

    const { getApiUrl } = require('../../config/config.js');
   
    wx.request({
      url: getApiUrl(`/api/course-schedule/${existingCourse.courseId}`),
      method: 'DELETE',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
     
     
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.code === 200) {
          // 删除成功，刷新课表
          this.hideAddCourseModal();
          
          // 立即从本地数据中移除该课程，避免等待服务器响应 (兼容微信小程序)
          const updatedSchedule = Object.assign({}, this.data.schedule);
          delete updatedSchedule[this.data.editingCourse];
          this.setData({ schedule: updatedSchedule }, () => {
            this.filterScheduleByWeek();
          });
          
          // 然后从服务器刷新最新数据
          this.refreshSchedule();
          
          // 清理未使用的颜色记录
          this.cleanupUnusedColors();
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          wx.vibrateShort();
        } else {
          wx.showToast({
            title: res.data?.msg || '删除失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 获取课程信息
  getCourseInfo: function(day, slot) {
    const courseKey = `${day}_${slot}`;
    return this.data.schedule[courseKey] || null;
  },

  // 为课程分配颜色
  assignColorToCourse: function(courseName) {
  
    const { usedColors, courseColors } = this.data;

    
    // 如果该课程名已经有颜色，直接返回
    if (usedColors[courseName]) {
     
      return usedColors[courseName];
    }
    
    // 获取已使用的颜色 (兼容微信小程序)
    const usedColorsList = [];
    for (let key in usedColors) {
      if (usedColors.hasOwnProperty(key)) {
        usedColorsList.push(usedColors[key]);
      }
    }

    
    // 找到第一个未使用的颜色 (兼容微信小程序)
    let availableColor = null;
    for (let i = 0; i < courseColors.length; i++) {
      const color = courseColors[i];
      if (usedColorsList.indexOf(color) === -1) {
        availableColor = color;
        break;
      }
    }
    
    
    // 如果所有颜色都被使用，随机选择一个
    if (!availableColor) {
      availableColor = courseColors[Math.floor(Math.random() * courseColors.length)];

    }
    
    // 记录颜色使用情况 (兼容微信小程序)
    const newUsedColors = Object.assign({}, usedColors);
    newUsedColors[courseName] = availableColor;
    

    this.setData({ usedColors: newUsedColors });
    
    return availableColor;
  },

  // 清理未使用的颜色记录
  cleanupUnusedColors: function() {
    const { schedule, usedColors } = this.data;
    const currentCourseNames = [];
    
    // 收集当前所有课程名 (兼容微信小程序)
    for (let key in schedule) {
      if (schedule.hasOwnProperty(key)) {
        const course = schedule[key];
        if (course && course.courseName) {
          if (currentCourseNames.indexOf(course.courseName) === -1) {
            currentCourseNames.push(course.courseName);
          }
        }
      }
    }
    
    // 清理不再使用的颜色记录
    const cleanedUsedColors = {};
    for (let courseName in usedColors) {
      if (usedColors.hasOwnProperty(courseName)) {
        if (currentCourseNames.indexOf(courseName) !== -1) {
          cleanedUsedColors[courseName] = usedColors[courseName];
        }
      }
    }
    
    this.setData({ usedColors: cleanedUsedColors });
  }
});
